package com.yxw.controller.exception;

import com.yxw.controller.MyResponse;
import com.yxw.controller.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class MyExceptionHandler {
    //处理算术异常
    @ExceptionHandler(ArithmeticException.class)
    public MyResponse zeroHandler(Exception e){
//        log.error(e.getMessage());
        System.out.println("出错信息: " + e.getMessage());
        return new MyResponse(ResultCode.ERROR,e.getMessage());
    }

    //处理Book类属性设置要求不符合要求的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public MyResponse handlerMethodArgumentNotValidException(MethodArgumentNotValidException e){
        //e.getBindingResult().getFieldError().getDefaultMessage()返回Book属性设置的message回显信息
        return new MyResponse(ResultCode.ERROR,e.getBindingResult().getFieldError().getDefaultMessage());
    }
}
